package com.yc.springmvc.core.filter;

import java.io.IOException;			

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.springmvc.core.util.StringUtil;





@WebFilter(filterName = "CharacterEncodingFilter", value = "/*",
	initParams = { @WebInitParam( name = "encoding", value = "UTF-8")})
public class CharacterEncodingFilter implements Filter{
	private String encoding = "UTF-8";
	
	
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		String temp = filterConfig.getInitParameter("encoding");
		if( !StringUtil.checkNull( temp )) {
			encoding = temp;
		}
	}



	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse )response;
		//给请求和响应都设置编码集 解决汉字的乱码问题
		req.setCharacterEncoding(encoding);
		resp.setCharacterEncoding(encoding);
		//链式调用下一个过滤器千万别漏掉 否则页面将一直徘徊在过滤器中 后续操作无法进行
		chain.doFilter(req, resp);
	}
	
}


